package com.jiajia.study.nio.chapter03;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * 一主多从
 */
public class MyNioReactorBossV2 {
    private static List<WorkerV2>  workers = new ArrayList<>();
    private static int number;
    static {
        number = 0;
        for (int i = 0; i < 4; i++) {
            workers.add(new WorkerV2("worker-" + i));
        }
    }
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress(8777));

        Selector selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (true){
            selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()){
                SelectionKey selectionKey = iterator.next();
                iterator.remove();
                if(selectionKey.isAcceptable()){
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    WorkerV2 workerV2 = workers.get(number % workers.size());
                    workerV2.register(socketChannel);
                    number++;
                }
            }
        }
    }
}
